package it.unibo.mumu;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import it.unibo.mumu.R;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
//import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import it.unibo.mumu.entity.Universe;
import it.unibo.mumu.util.AddressUrl;
import it.unibo.mumu.util.Downloader;
import it.unibo.mumu.util.ParseXmlSelectedUniverse;
import it.unibo.mumu.util.ParseXmlUniverse;
import it.unibo.mumu.util.SingletonSupport;

public class StartActivity extends Activity {

	private Context context;

	private LinearLayout avatarContainer;
	private ImageButton removeUniverseBtn;
	private ImageButton playBtn;
	private boolean universePresence;
	private AddressUrl addressUrl;
	
	private boolean switching;
	
	private MediaPlayer mp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_start);
		switching = false;
		addressUrl = new AddressUrl();
		
		avatarContainer = (LinearLayout) findViewById(R.id.avatarContainer);

		removeUniverseBtn = (ImageButton) findViewById(R.id.removeUniverseBtn);
		playBtn = (ImageButton) findViewById(R.id.playBtn);

		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			avatarContainer.setOrientation(LinearLayout.HORIZONTAL);
		} else {
			avatarContainer.setOrientation(LinearLayout.VERTICAL);
		}

		// controllo se ci sono universi nella cartella/XML
		File directory = getFilesDir();
		File universesFile = new File(directory + "/universes.xml");
		universePresence = universesFile.exists();
		
		// cartella vuota
//		if (contents.length == 0) {
//			universePresence = false;
//			Log.i("APPTEST", "cartella vuota");
//		}
//		// cartella contiene file
//		else {
//			universePresence = true;
			
//		}
		//universePresence = true; // debug
		if (!universePresence) {
			
			// se non ci sono
			removeUniverseBtn.setVisibility(View.GONE); // guardare
			playBtn.setOnClickListener(getListUniverseListener());
			// setta il listener
		} else {
			// se ci sono 
			
			// mettere il parser che popola singleton
			SingletonSupport.getInstance().clearAll();
			
			ParseXmlUniverse parser = new ParseXmlUniverse();
        	InputStream inputStream = null;
			try {
				inputStream = openFileInput("universeList.xml");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	List<Universe> universes = parser.parse(inputStream);
        	for(int i=0; i<universes.size();i++){
        		SingletonSupport.getInstance().addSimpleUniverse(universes.get(i));	
        	}
        	
			
			ParseXmlSelectedUniverse parser2 = new ParseXmlSelectedUniverse();
        	parser2.parse(getFilesDir().toString());
//			Log.i("APPTEST", "cartella contiene file");
			
			playBtn.setVisibility(View.GONE);
			removeUniverseBtn.setOnClickListener(getRemoveMultiverseListener());
			
			UniverseAvatar currentUniverse;
			
			SingletonSupport support = SingletonSupport.getInstance();
			
			
			for (int i = 0; i < support.getUniverses().size(); i++){
				currentUniverse = new UniverseAvatar(getApplicationContext(), support.getUniverses().get(i).getId(),
						support.getUniverses().get(i).getName(), getFilesDir() + "/" + getAvatarPath(support.getUniverses().get(i).getId()));
				LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);
				llp.setMargins(24, 0, 24, 0);
				llp.gravity = Gravity.CENTER_HORIZONTAL;
				currentUniverse.getUniverseImageButton().setOnClickListener(getNewUniverseListener());
				avatarContainer.addView(currentUniverse, llp);
			}

		}
		playBgMusic();
	}
	
	private void playBgMusic() {
	    mp = MediaPlayer.create(this,
	            R.raw.intro);
	    mp.start();
	    mp.setOnCompletionListener(new OnCompletionListener() {

	        @Override
	        public void onCompletion(MediaPlayer mp) {
	            mp.release();
	        }

	    });

	}
	
	@Override
	protected void onPause() {
		mp.pause();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		mp.start();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mp.release();
		super.onDestroy();
	}
	
	private String getAvatarPath(int id){
		SingletonSupport support = SingletonSupport.getInstance();
		
		String path = "";
		
		ArrayList<Universe> universeList = support.getSimpleUniverses();
		for(int i=0; i<universeList.size(); i++){
			if(universeList.get(i).getId() == id){
				path = universeList.get(i).getAvatarpath();
				break;
			}
		}
		if(path.equals("")){
			return "android.resource://" + getPackageName() + "/" + R.drawable.start_button_hover;
		}else{
			return path;
		}
		
	}
	
	private View.OnClickListener getNewUniverseListener(){
		View.OnClickListener listener = new View.OnClickListener() {
			public void onClick(View v) {
				if(switching)
					return;
				switching = true;
				UniverseAvatar u = (UniverseAvatar)v.getParent();
				// container.scrollTo(0, 0);
				// TODO: far partire l'intent qui
//				Toast.makeText(
//						getApplicationContext(),
//						"Cliccato " + u.getLabelText() + " con id: " + u.getIdUniverse(), Toast.LENGTH_LONG).show();
				Intent toUniverse = new Intent(StartActivity.this,
						GalaxyActivity.class);
				
				SingletonSupport support = SingletonSupport.getInstance();
				support.setUniverseID(u.getIdUniverse());
				
//				toUniverse.putExtra("UNIVERSE_ID", );
				System.gc();
				finish();
				startActivity(toUniverse);
			}
		};
		return listener;
	}
	
	private View.OnClickListener getListUniverseListener(){
		View.OnClickListener listener = new View.OnClickListener() {
			public void onClick(View v) {
				if(switching)
					return;
				switching = true;
//				Toast.makeText(getApplicationContext(),"Caricamento in corso...", Toast.LENGTH_LONG).show();
				
				AlertDialog.Builder builder = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_DARK);
				builder.setMessage("Caricamento in corso...").setTitle("Contatto il server");
				builder.setCancelable(false);
				final AlertDialog dialog = builder.create();
				dialog.show();
				
				new Thread(new Runnable() {
                    public void run() {
                    	Downloader downloadXmlUniverses = new Downloader(context);
                    	downloadXmlUniverses.downloadResource(addressUrl.getUrl_XmlAllUniverses(), "universeList.xml", getFilesDir().toString());
                    	
                    	Downloader downloadAvatar = new Downloader(context);
                    	downloadAvatar.downloadResourceAndUnzip(addressUrl.getUrl_AvatarZip(), "avatar.zip", getFilesDir().toString());
                    	
                    	if(downloadXmlUniverses.getError() == null && downloadAvatar.getError() == null ){
	                    	Intent toSelectUniverses = new Intent(StartActivity.this, SelectUniverses.class);
	                    	System.gc();
	        				finish();
	        		        startActivity(toSelectUniverses);
                    	} else {
                    		((Activity)context).runOnUiThread(new Runnable() {

								@Override
								public void run() {
									dialog.dismiss();
		                    		AlertDialog.Builder builder2 = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_DARK);
		                    		builder2.setMessage("Non riesco a collegarmi al server, sei sicuro che sia attiva una connessione internet?").setTitle("Errore di connessione");
		                    		builder2.setCancelable(true);
		                    		AlertDialog dialog2 = builder2.create();
		                    		dialog2.show();
		                    		switching = false;
								}
                    			
                    		});
                    		
                    	}
          	     }
                }).start();
				
			}
		};
		return listener;
	}
	
	private View.OnClickListener getRemoveMultiverseListener(){
		View.OnClickListener listener = new View.OnClickListener() {
			public void onClick(View v) {
				if(switching)
					return;
				switching = true;
				// TODO: far partire l'intent qui
				Toast.makeText(
						getApplicationContext(),
						"Elimino tutti gli universi!", Toast.LENGTH_SHORT).show();
				// sega tutto
				DeleteRecursive(getFilesDir());
				SingletonSupport support = SingletonSupport.getInstance();
				support.clearAll();
				
				Intent i = getIntent();
				System.gc();
				finish();
				startActivity(i);
			}
		};
		return listener;
	}
	
	private void DeleteRecursive(File fileOrDirectory) {

		if (fileOrDirectory.isDirectory())
		    for (File child : fileOrDirectory.listFiles())
		        DeleteRecursive(child);

		    fileOrDirectory.delete();

    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.start, menu);
		return true;
	}

	public void onConfigurationChanged(Configuration c) {
		super.onConfigurationChanged(c);
		if (c.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			avatarContainer.setOrientation(LinearLayout.HORIZONTAL);
		} else {
			avatarContainer.setOrientation(LinearLayout.VERTICAL);
		}
	}
}
